package com.anyonavinfo.cpaddemo.data.appinfo.source;




import com.anyonavinfo.cpaddemo.data.appinfo.AppInfo;
import com.anyonavinfo.cpaddemo.data.appinfo.source.local.AppInfoLocalDataSource;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZuiC on 2017/1/18.
 */

public class AppInfoRepository implements AppInfoDataSource{

    private List<AppInfo> mCacheInstalledAppInfo;
    private List<AppInfo> mCacheAllAppInfo;
    private boolean mCacheDirty = false;

    private static AppInfoRepository INSTANCE = null;
    private int mInstalledAppNum;


    public static AppInfoRepository getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new AppInfoRepository();
        }
        return INSTANCE;
    }

    private AppInfoRepository(){

    }


    @Override
    public void loadInstalledAppInfo(LoadInstalledAppInfoCallBack callBack) {
        if (mCacheInstalledAppInfo == null || mCacheDirty){
            loadAppInfo();
        }
        callBack.getInstalledAppInfo(mCacheInstalledAppInfo);
    }

    private void loadAppInfo() {
        if (mCacheAllAppInfo == null || mCacheDirty){
            mCacheAllAppInfo = AppInfoLocalDataSource.getInstance().getAppInfo();
        }

        if (mCacheInstalledAppInfo == null || mCacheDirty){
            mCacheInstalledAppInfo = new ArrayList<>();
            mInstalledAppNum = 0;
            for (int i = 0; i < mCacheAllAppInfo.size(); i++){
                if (mCacheAllAppInfo.get(i).getIsInstalled()){
                    mInstalledAppNum++;
                    mCacheInstalledAppInfo.add(mCacheAllAppInfo.get(i));
                }
            }
        }
        mCacheDirty = false;
    }

    @Override
    public void loadAppInfo(LoadAppInfoCallBack callBack) {
        if (mCacheInstalledAppInfo == null || mCacheAllAppInfo == null || mCacheDirty){
            loadAppInfo();
        }
        callBack.getInstalledAppNum(mInstalledAppNum);
    }

    @Override
    public void reloadAppInfo() {
        mCacheDirty = true;
    }
}
